package com.hfzy.ihk.common.eventSocket.context;

import com.alibaba.fastjson.JSON;
import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.inbound.InboundConnectionFailure;
import org.freeswitch.esl.client.internal.Context;
import org.freeswitch.esl.client.internal.IModEslApi;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import java.net.InetSocketAddress;
import java.util.Map;

/**
 * Created by Administrator on 2019/7/11.
 */
public abstract class EventSocketInit implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(EventSocketInit.class);

    private Client client;

    protected abstract String getHost();

    protected abstract int getPort();

    protected abstract String getPassword();

    @Override
    public void afterPropertiesSet() throws Exception {
        client = initClient();
    }

    public Client initClient(){
        client = new Client();

        try {
            client.connect(new InetSocketAddress(getHost(), getPort()), getPassword(), 10);

        } catch (InboundConnectionFailure e) {
            logger.error("freeswitchlog : freeswitch连接eventSocket失败", e);
            logger.error("Connect failed", e);
            return null;
        }

        //注册事件处理程序
        client.addEventListener((Context context, EslEvent event)->{
            try {

                String eventName = event.getEventHeaders().get("Event-Name");

                logger.debug("eventName:"+eventName+"-->消息队列接受中间状态完整消息：" + JSON.toJSONString(event));

                //获取所有的头信息
                Map<String, String> eventHeaders = event.getEventHeaders();
                //获取sessionId,语音识别的状态是没有Channel-Call-UUID,只有session_id
                String sessionId = eventHeaders.get("Channel-Call-UUID")==null?eventHeaders.get("session_id")==null?eventHeaders.get("sessionId"):eventHeaders.get("session_id"):eventHeaders.get("Channel-Call-UUID");

                if (sessionId != null) {
                    //判断是否是本服务发起
                    if(!hasSessionId(sessionId,event)){
                        return;
                    }

                    //通过sessionId判断进入那个队列
                    stateProcessing(event);
                }

                eventProcessing(event);

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("初始化接受呼叫中间状态队列异常");

            }
        }
        );

        client.setEventSubscriptions(IModEslApi.EventFormat.PLAIN, getEvents());

        System.out.println("freeswitchlog : freeswitch连接成功!!");

        return client;
    }


    /**
     * 处理事件逻辑
     * @param event
     */
    protected abstract void eventProcessing(EslEvent event);

    /**
     * 需要订阅的事件
     * @return
     */
    protected abstract String getEvents();

    /**
     * 判断当前通道是否该进入该客户端
     * @param sessionId
     * @return
     */
    public abstract boolean hasCall(String sessionId);

    /**
     * 当sessionId不为空时怎么处理
     * @param sessionId
     */
    protected boolean hasSessionId(String sessionId,EslEvent event){
        if (!hasCall(sessionId)) {
            logger.info("本次通话不是由此服务发起,所以不处理,sessionId:" + sessionId);

            return false;
        }
        return true;
    }

    /**
     * 中间状态处理
     */
    protected abstract void stateProcessing(EslEvent event);

    public Client getClient() {
        return client;
    }

}
